package com.dobest.base.collection;

import com.dobest.utils.PrintUtils;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @author huangy
 * @description
 * @since 2022/11/17 17:19
 **/
public class MapTest {

    @Data
    static class A {
        private int a;
        private String b;

        public A() {
            this.a = 0;
            this.b = "123";
        }

        public A(int a, String b) {
            this.a = a;
            this.b = b;
        }
    }

    @Test
    public void mapSplit() {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < 5; i++) {
            map.put(i + 1, i + 1);
        }
        List<Map<Integer, Integer>> maps = partition(map, 5);
        maps.forEach(map0 -> {
            System.out.println("map大小:" + map0.size());
            PrintUtils.printMap(map0);
        });
    }

    public static <K, V> List<Map<K, V>> partition(Map<K, V> map, int size) {
        List<Map<K, V>> mapList = new ArrayList<>();
        int mapSize = map.size();
        if (mapSize <= size) {
            mapList.add(map);
        } else {
            int mapNum = mapSize / size;
            if (mapSize % size > 0) {
                mapNum += 1;
            }
            //初始化map数量
            for (int i = 0; i < mapNum; i++) {
                mapList.add(new HashMap<>());
            }
            List<K> keys = map.keySet().stream().toList();
            for (int i = 0; i < keys.size(); i++) {
                K key = keys.get(i);
                mapList.get(i / size).put(key, map.get(key));
            }
        }
        return mapList;
    }

    @Test
    public void computeTest() {
        A a1 = new A();
        Map<Integer, A> aMap = new HashMap<>();
        aMap.put(a1.getA(), a1);
        A a2 = aMap.computeIfAbsent(2, a -> new A(7,"aaaa"));
        System.out.println(a2.a + ":" + a2.b);
        A a3 = aMap.computeIfAbsent(2, a -> new A(3, "5"));
        System.out.println(a3.a + ":" + a3.b);
    }

}
